package org.obm.delivery.cassandra.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.apache.james.mime4j.dom.Message;
import org.obm.bigg.model.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Prepares a message for writing into cassandra
 * 
 * @author tom
 * 
 */
public class MessageDenormalizer {

	private Message m;
	private Logger logger = LoggerFactory.getLogger(getClass());

	private String messagesKey;
	private HashMap<String, String> messagesInfo;
	private HashSet<String> refs;

	public MessageDenormalizer(Message m) {
		this.m = m;
		this.messagesInfo = new HashMap<String, String>();
	}

	public BlownUpMessage blowUpInto(String folder) {
		BlownUpMessage bum = new BlownUpMessage();

		logger.info("blowing up message " + m.getMessageId());
		extractMessagesCF();

		bum.setMessagesInfo(messagesKey, messagesInfo);

		extractThreadingInfo();

		StructureHelper bodyHelper = new StructureHelper(m, bum);
		bodyHelper.extractStructure();

		return bum;
	}

	private void extractThreadingInfo() {
		refs = new HashSet<String>();
		String irt = DenormHelper.header(m, "In-Reply-To");
		if (irt != null) {
			refs.add(irt);
		}
		String references = DenormHelper.header(m, "References");
		if (references != null) {
			String[] r = references.split(" ");
			for (String ref : r) {
				refs.add(ref);
			}
		}
	}

	private void extractMessagesCF() {
		messagesKey = m.getMessageId();
		messagesInfo.put(Messages.SUBJECT, m.getSubject());
		if (m.getSender() != null) {
			messagesInfo.put(Messages.FROM, m.getSender().getDisplayString());
		}

		messagesInfo.put(Messages.TO, DenormHelper.addrList(m.getTo()));
		messagesInfo.put(Messages.CC, DenormHelper.addrList(m.getCc()));
		messagesInfo.put(Messages.BCC, DenormHelper.addrList(m.getBcc()));
		
		messagesInfo.put(Messages.READ, "false");
		messagesInfo.put(Messages.FLAGGED, "false");
		messagesInfo.put(Messages.ANSWERED, "false");
		// TODO Auto-generated method stub

	}

	public Set<String> getRefs() {
		return refs;
	}

}
